package com.javabasic.algorithm.leetcode;

/**
 * @author mir.xiong
 * @version 1.0
 * @description
 * @see [1034. Coloring A Border](https://leetcode-cn.com/problems/coloring-a-border/)
 * @since Created by work on 2021/12/7 11:31 下午
 */
public class ColoringABorder {

    final int NEXT_ROW = 4;
    /**
     * 上、右、下、左  -- 0、1、2、3
     */
    int[][] next = new int[][]{{-1, 0}, {0, 1}, {1, 0}, {0, -1}};

    public int[][] colorBorder(int[][] grid, int row, int col, int color) {
        int lenRow = grid.length;
        int lenCol = grid[0].length;
        coloration(grid, lenRow, lenCol, row, col, color);
        return grid;
    }

    private void coloration(int[][] grid, int lenRow, int lenCol, int row, int col, int color) {


        int tempCol, tempRow, evenNum = 0, oddNum = 0;
        for (int i = 0; i < NEXT_ROW; i++) {
            tempRow = row + next[i][0];
            tempCol = col + next[i][1];
            if (checkCoordinate(tempRow, tempCol, lenRow, lenCol) && grid[row][col] != grid[tempRow][tempCol]) {
                if ((i & 1) == 1) {
                    oddNum++;
                } else {
                    evenNum++;
                }
            }
        }
        if (oddNum == 0 || evenNum == 0) {
            grid[row][col] = color;
        }
        for (int i = 0; i < NEXT_ROW; i++) {
            tempRow = row + next[i][0];
            tempCol = col + next[i][1];
            if (checkCoordinate(tempRow, tempCol, lenRow, lenCol)) {
                coloration(grid, lenRow, lenCol, tempRow, tempCol, color);
            }
        }
    }

    /**
     * 检查坐标位置
     *
     * @param tempRow
     * @param tempCol
     * @param lenRow
     * @param lenCol
     * @return
     */
    private boolean checkCoordinate(int tempRow, int tempCol, int lenRow, int lenCol) {
        if (tempRow < 0 || tempRow >= lenRow || tempCol < 0 || tempCol >= lenCol) {
            return false;
        }
        return true;
    }
}
